/**
 * Created by Administrator on 2017/8/29.
 */
/**
 * Created by Administrator on 2017/8/29.
 */
var map;
var busutil;

var hasbusNo01 = false;
var curItemNo01 = window.localStorage.getItem("curItemNo01");
if(curItemNo01 == null){
    curItemNo01 = 0;
    window.localStorage.setItem("curItemNo01", curItemNo01);
}
var busNo01 = window.localStorage.getItem("busNo01");
if(busNo01 != null){
    hasbusNo01 = true;
}
var haskeyword01 = false;
var keyword01 = window.localStorage.getItem("keyword01");
if(keyword01 != null){
    haskeyword01 = true;
}

var mySwiper;
var stationArr = [];
var stopCount;

$(document).ready(function () {
    initMap();
    initControl();

    //对面板进行声明
    $( "#searchpanel" ).trigger( "updatelayout" );
    $( "#resultpanel" ).trigger( "updatelayout" );

    busutil = new BMap.BusLineSearch("杭州", {
        renderOptions: {panel: "itemResult"},
        onGetBusListComplete: function (buslist) {
            //考虑环线
            if(buslist.getBusListItem(curItemNo01)==undefined){
                curItemNo01 = 0;
                window.localStorage.setItem('curItemNo01', curItemNo01);
            }
            busutil.getBusLine(buslist.getBusListItem(curItemNo01));
        },
        onGetBusLineComplete: function (busline) {
            //写线路的基本信息
            var index = busline.name.indexOf('(');
            var htmlTitle = busline.name.substring(0, index);
            $("#title").html(htmlTitle);

            var htmlPoints =
                '<div style="height: 40px;font-size:14px;"><img src="img/icons-road.png"style="width:22px;height:22px;vertical-align: middle;margin-right: 6px;">' + busline.name.substring(index + 1, busline.name.length - 1) + '</div>';

            var htmlTimes =
                '<div style="font-size: 12px;"><span style="color: #169bdb;">●</span><span>首班：' + busline.startTime
                + '</span><span style="color: #f77446;margin-left: 6px;">●</span><span>末班：' + busline.endTime +
                '</span><span style="margin-left: 6px;">票价：2元</span></div>';

            $.ajax({
                url: 'http://127.0.0.1:8083/app-server/busStationInfo',
//                data: {"SL_id":sl_id},
                type: 'get',
                datatype: 'json',
                async: 'false',
                success: function (json) {
                    var busInfoList = json.station;
                    var nextStopArr = [];
                    var stopCountArr = [];
                    var stopTimeArr = [];
                    var stopDistanceArr = [];
                    for (var i in busInfoList) {
                        nextStopArr[i] = busInfoList[i].nextstop;
                        stopCountArr[i] = busInfoList[i].stopcount;
                        stopTimeArr[i] = busInfoList[i].distance;
                        stopDistanceArr[i] = busInfoList[i].time;
                    }
                    htmlTable =
                        '<div><table><tr><td align="center">最近的第1辆公交</td><td align="center">最近的第2辆公交</td></tr><tr><th colspan="2" style="border-bottom: 1px #2c2c2c solid"></th></tr><tr><td align="center">'+ stopCountArr[0] +'站</td><td align="center">'+ stopCountArr[1] +'站</td></tr><tr><td align="center">开往 '+ nextStopArr[0] +'</td><td align="center">到达 '+ nextStopArr[1] +'</td></tr><tr><td align="center">'+stopTimeArr[0]+'/'+ stopDistanceArr[0] +'</td><td align="center">'+stopTimeArr[1]+'/'+ stopDistanceArr[1] +'</td></tr><tr><th colspan="2" style="border-bottom: 1px #2c2c2c solid"></th></tr></table></div>';
                    $('.thumbs-title').html(htmlPoints + htmlTimes + htmlTable);
                }
            });

            //需要来画地图列表了
            var stations = busline.RB;
            var html = [];
            for(var i in stations){
                stationArr[i] = stations[i].name;
                if(stations[i].name==keyword01){
                    html.push('<div class="swiper-slide"><img src="img/icons-pic-select.png" onclick="divClick(this)" alt=""><div class="app-title">' +
                        stations[i].name + '</div></div>');
                }else{
                    html.push('<div class="swiper-slide"><img src="img/icons-pic.png"  onclick="divClick(this)" alt=""><div class="app-title">' +
                        stations[i].name + '</div></div>');
                }
            }

            /*$('.swiper-container').css("height", '100px');
             $('.swiper-container').css("height", '2000px');
             $('.swiper-wrapper').css("height", '100px');*/
            // $('.swiper-wrapper').css("width", '2000px');
            $('.swiper-wrapper').html(html);

            $('.thumbs-cotnainer').each(function (value,index) {
                mySwiper = $(this).swiper({
                    slidesPerView: 'auto',
                    offsetPxBefore: 25,
                    offsetPxAfter: 10,
                    calculateHeight: true,
                    setWrapperSize: true,
                    freeMode: true
                })
            });
            getStopCount();
            mySwiper.swipeTo(stopCount,500,false);
        },
        onBusLineHtmlSet: function () {
            //线路格式化完毕时 才执行 所以在这里添加marker是不能显示的
            $("#l-result ul li a").each(function (index, element) {
                if ($(element).html() != busNo01) {
                    $(element).css("color", "green");
                } else {
                    $(element).css("color", "blue");
                }
            });
        }
    });

    var img = document.createElement("img");
    img.style.cursor = 'pointer';
    img.setAttribute('src', 'img/reversebutton.png');
    img.setAttribute('width', '40px');
    img.setAttribute('height', '40px');
    /*    img.setAttribute('right', '0px');
     img.setAttribute('bottom', '80px');
     img.setAttribute('position', 'fixed');*/
    img.setAttribute('class', 'float');
    $("#busStationSearchListContent").append(img);
    img.onclick = function (e) {
        curItemNo01 = 1 - curItemNo01;
        window.localStorage.setItem('curItemNo01', curItemNo01);
        busutil.getBusList(busNo01);
    };

    if(hasbusNo01&&haskeyword01){
        $("#map").css("display", "none");
        new BMap.LocalSearch("杭州", {
            onSearchComplete: function () {
                busutil.getBusList(busNo01);
            }
        }).search(keyword01);
        hasbusNo01 = false;
        haskeyword01 = false;
    }

    document.getElementById('query').onclick = function () {
        map.clearOverlays();
        keyword01 = $("#keyword01").val();
        window.localStorage.setItem('keyword01', keyword01);
        new BMap.LocalSearch("杭州", {
            onSearchComplete: searchComplete
        }).search(document.getElementById('keyword01').value+"公交车站");

        $("#keyword01").val("");
        $("#searchpanel").panel("close");
        $("#resultpanel").panel("open");
    };
});

function getStopCount() {
    for(var i in stationArr){
        if(stationArr[i]==keyword01){
            stopCount = i;
        }
    }
}

function searchComplete(result) {
    var html = [];
    for (var i = 0; i < result.getCurrentNumPois(); i++) {
        var poi = result.getPoi(i);
        if (poi.type == BMAP_POI_TYPE_BUSSTOP) {
            var busNames = poi.address.split(';');
            for (i = 0; i < busNames.length; i++) {
                //获得了所有的busName 把它写到div中
                html.push('<li><a href="javascript:void(0)" onclick="subgo(\'' + busNames[i] + '\')">' +
                    busNames[i] +
                    '</a></li>');
            }
        } else {

        }
    }
    var l_result = document.getElementById("l-result");
    l_result.innerHTML = '<ul>' + html.join('') + '</ul>';
}

function subgo(itemNo) {
    $("#map").css("display", "none");
    busNo01 = itemNo;
    window.localStorage.setItem("busNo01", busNo01);
    busutil.getBusList(busNo01);
}

function divClick(item) {
    //首先判断是否有使用select icon的img 将其还原  遍历
    $('.swiper-wrapper img').each(function (index,val) {
        if($(val).attr('src')=='img/icons-pic-select.png') {
            $(val).attr('src', 'img/icons-pic.png');
            return false;
        }
    });

    //设置此img
    $(item).attr('src',"img/icons-pic-select.png");
    $(item).next().css('color', '#ff8d30');
    keyword01 = $(item).next().html();
    window.localStorage.setItem('keyword01', keyword01);

    //ajax更改实时信息
    $.ajax({
        url: 'http://10.100.122.132/busStationInfo',
//                data: {"SL_id":sl_id},
        type: 'get',
        datatype: 'json',
        async: 'false',
        success: function (json) {
            var busInfoList = json.station;
            var nextStopArr = [];
            var stopCountArr = [];
            var stopTimeArr = [];
            var stopDistanceArr = [];
            for (var i in busInfoList) {
                nextStopArr[i] = busInfoList[i].nextstop;
                stopCountArr[i] = busInfoList[i].stopcount;
                stopTimeArr[i] = busInfoList[i].distance;
                stopDistanceArr[i] = busInfoList[i].time;
            }
            htmlTable =
                '<div><table><tr><td align="center">最近的第1辆公交</td><td align="center">最近的第2辆公交</td></tr><tr><th colspan="2" style="border-bottom: 1px #2c2c2c solid"></th></tr><tr><td align="center">'+ stopCountArr[0] +'站</td><td align="center">'+ stopCountArr[1] +'站</td></tr><tr><td align="center">开往 '+ nextStopArr[0] +'</td><td align="center">到达 '+ nextStopArr[1] +'</td></tr><tr><td align="center">'+stopTimeArr[0]+'/'+ stopDistanceArr[0] +'</td><td align="center">'+stopTimeArr[1]+'/'+ stopDistanceArr[1] +'</td></tr><tr><th colspan="2" style="border-bottom: 1px #2c2c2c solid"></th></tr></table></div>';
            $('.thumbs-title div:last').remove();
            $('.thumbs-title').append($(htmlTable));
        }
    });
}

//初始化地图
initMap = function () {
    var mapOpts = {minZoom: 11, maxZoom: 17, enableHighResolution: true};
    map = new BMap.Map('map', mapOpts);
    map.centerAndZoom("杭州");
};

//初始化地图控件
initControl = function () {
    var navOpts = {anchor: BMAP_ANCHOR_BOTTOM_RIGHT, offset: new BMap.Size(50, 40), type: BMAP_NAVIGATION_CONTROL_ZOOM};
    var nav = new BMap.NavigationControl(navOpts);
    map.addControl(nav);

    /*    var scale = new BMap.ScaleControl();
     map.addControl(scale);*/

    var overOpts = {
        anchor: BMAP_ANCHOR_TOP_LEFT,
        offset: new BMap.Size(10, 10),
        size: new BMap.Size(100, 100),
        isOpen: false
    };
    var over = new BMap.OverviewMapControl(overOpts);
    map.addControl(over);

    /*    var mapTypeC = new BMap.MapTypeControl();
     map.addControl(mapTypeC);*/
};